﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace autobackup.util
{
    class FileUtil
    {
        public static int total = 0;

        public static int noCopy = 0;

        public static void startCopy(string srcdir, string desdir)
        {
            total = 0;
            noCopy = 0;
            CopyDirectory(srcdir, desdir);
        }

        public static void startMutilCopy(string[] srcDirs,string desdir)
        {
            total = 0;
            noCopy = 0;
            foreach (string src1 in srcDirs)
            {
                CopyDirectory(src1, desdir);
            }
        }

        public static void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);

            string desfolderdir = desdir + "\\" + folderName;

            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);

            foreach (string file in filenames)// 遍历所有的文件和目录
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {

                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }

                    CopyDirectory(file, desfolderdir);
                }

                else // 否则直接copy文件
                {
                    string desfileName = file.Substring(file.LastIndexOf("\\") + 1);

                    desfileName = desfolderdir + "\\" + desfileName;


                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }

                    FileInfo fiSrc = new FileInfo(file);
                    FileInfo fiDes = new FileInfo(desfileName);

                    if (DateTime.Compare(fiSrc.LastWriteTime, fiDes.LastWriteTime) > 0)
                    {
                        fiSrc.CopyTo(desfileName, true);
                        total++;//文件处理总数+1
                        //File.Copy(file, desfileName, true);//第三个参数覆盖文件。
                    }
                    else
                    {
                        noCopy++;
                    }
                }
            }//foreach 
        }//function end
    }
}
